package light.head.config;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import light.head.cache.Cache;
import light.head.framework.entity.Template;
import light.head.framework.utils.XmlUtils;

import org.dom4j.Document;
import org.dom4j.Element;

public class TemplateParm {
	private final static String path = "/config/template.xml";
	
	private final static String CODE = "code";
	private final static String NAME = "name";
	private final static String CONTENT = "content";

	@SuppressWarnings("unchecked")
	public static boolean loadAll() {
		Document xml = loadHandleXml();
		Element element = xml.getRootElement();

		if (null != element && element.elements().size() > 0) {
			List<Template> list = new ArrayList<Template>();
			Template tem = null;
			for (Iterator<Element> basicList = element.elementIterator();basicList.hasNext();) {
				Element basic = basicList.next();
				tem = new Template();
				for (Iterator<Element> sonList = basic.elementIterator();sonList.hasNext();) {
					Element son = sonList.next();
					if (null != son) {
						if(CODE.equals(son.getName()))
							tem.setCode(son.getText());
						if(CONTENT.equals(son.getName()))
							tem.setContent(son.getText());
						if(NAME.equals(son.getName()))
							tem.setName(son.getText());
					}
				}
				list.add(tem);
			}
			Cache.templateList = list;
			return true;
		}
		return false;
	}
	
	
	public static Document loadHandleXml() {
		InputStream in = Config.class.getResourceAsStream(path);
		Document xml = XmlUtils.loadXML(in);
		return xml;
	}
}
